// pages/IDCard/openDoor.js
const app = getApp();

import inBleOpen from './js/InBleOpen.js';
import peakeBleOpen from './js/PeakeBleOpen.js';
import bosinyBleOpen from './js/BosinyBleOpen.js';
import bluetoothSortingScan from './js/BluetoothSortingScan.js';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    // 组件参数设置，传递到组件
    defaultData: {
      title: "一键开门", // 导航栏标题
      showHome: false, //是否显示回到首页按钮
      showBack: true, //是否显示返回按钮
      showLogo: false, //是否显示logo
      bgColor: 'transparent'
    },
    baseUrl: app.baseUrl,
    version: app.globalData.version,
    navBarHeight: app.globalData.navBarHeight,

    shareTitle: '',
    shareImg: '',
    openid: '',
    is_register: 0,
    mySf: '',

    actions: [], //通过权限验证的设备列表
    deviceList: [], //蓝牙扫描到的门禁设备列表
    isFirst: true, //是否是第一次使用
    currentStatus: {}, //当前的状态及提示
    status: {
      searching: {
        type: 'searching',
        tip: '正在连接',
        subtip: '正在搜索蓝牙设备'
      },
      opening: {
        type: 'open',
        tip: '连接成功,请选择门禁',
        subtip: '选择后,点击圆圈按钮即可开锁'
      },
      open: {
        type: 'open',
        tip: '一键开锁',
        subtip: '请点击上方按钮选择开锁'
      },
      success: {
        type: 'success',
        tip: '开锁成功',
        subtip: '已成功开锁,请通行'
      },
      fail: {
        type: 'fail',
        tip: '开锁失败',
        subtip: '请联系物业人员'
      },
      cannotConnect: {
        type: 'cannotConnect',
        tip: '搜索失败',
        subtip: '请开启蓝牙后点击按钮重新搜索'
      },
      noDivice: {
        type: 'cannotConnects',
        tip: '搜索失败',
        subtip: '点击按钮可重新搜索'
      },
    },
    door: '请选择门禁',
    selectInfo: {}, //选择的开门门禁信息
    clickOpen:false,
  },

  //点击查看开锁日志
  record() {
    wx.navigateTo({
      url: '/pages/IDCard/openDoorRecord',
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    var that = this;

    //获取缓存中的openid"oZYOb4jQ1cdq3ZdTqRcQX4r_BI5Y"//
    var openid = wx.getStorageSync('ly24_openid');

    if (openid == '') {
      //缓存中没有openid
      //获取所需页面信息
      wx.login({
        success: function(res) {
          if (res.code) {
            //发起网络请求
            wx.request({
              url: that.data.baseUrl + 'getOpenid.php',
              method: 'POST',
              data: {
                'code': res.code
              },
              header: {
                'content-type': 'application/x-www-form-urlencoded'
              },
              success: function(res) {
                //缓存微信openid
                wx.setStorageSync('ly24_openid', res.data.openid);
                that.setData({
                  openid: res.data.openid
                });

                //获取本页数据
                that.getDoorPageInfo(res.data.openid);
              },
              fail: function(res) {}
            });
          }
        }
      });
    } else {
      that.setData({
        openid: openid
      });

      //获取本页数据
      that.getDoorPageInfo(openid);
    }

    //调用分享
    that.getShareInfo();
  },

  //获取本业数据
  getDoorPageInfo(openid) {
    var that = this;
    wx.showLoading({
      title: '数据加载中...'
    })
    wx.request({
      url: that.data.baseUrl + 'getDoorPageInfo.php',
      method: 'POST',
      data: {
        'openid': openid
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function(res) {
        wx.hideLoading();
        if (res.data.status == 1) {
          //重新赋值后台请求数据
          that.setData({
            currentStatus: that.data.status.searching //初始化页面状态
            //currentStatus: that.data.status.success //初始化页面状态
          });

          //调用启动蓝牙检测
          that.startBlue();
        } else {
          app.showTip(res.data.msg);
          setTimeout(function() {
            wx.navigateBack({
              delta: 1
            });
          }, 1500);
        }
      },
      fail: function() {
        wx.hideLoading();
        app.showTip('抱歉,服务器繁忙');
        setTimeout(function() {
          wx.navigateBack({
            delta: 1
          });
        }, 2000);
      }
    });
  },

  //点击重新搜索
  resetSearch() {
    this.setData({
      currentStatus: this.data.status.searching //重新初始化页面状态
    });

    //调用启动蓝牙设备重新搜索
    this.startBlue();
  },

  //启动蓝牙检测
  startBlue() {
    const that = this;

    wx.openBluetoothAdapter({
      success() {
        that.getAdapterState()
      },
      fail: function(res) {
        wx.showModal({
          content: '请开启手机蓝牙后再试'
        })

        that.setData({
          currentStatus: that.data.status.cannotConnect
        })
        wx.onBluetoothAdapterStateChange(function(res) { //监听蓝牙打开关闭
          if (res.available) {
            that.setData({
              currentStatus: that.data.status.searching
            })
            console.log("用户已手动开启蓝牙，检查是否可用")
            that.getAdapterState();
          }
        })
      }
    })
  },

  //获取当前蓝牙状态
  getAdapterState() {
    const that = this
    wx.getBluetoothAdapterState({
      success: function(res) {
        console.log('蓝牙状态', res);
        //discovering 是否正在搜索设备  available 蓝牙适配器是否可用
        if (res.available == false) {
          that.setData({
            currentStatus: that.data.status.cannotConnect
          })
          app.showTip("当前蓝牙不可用");
        } else if (res.discovering == false) {
          that.scanBluetoothDevice();
        } else if (res.available) {
          that.scanBluetoothDevice();
        }
      },
      fail() {
        app.showTip("当前蓝牙不可用,请断开其他连接重试");
        that.setData({
          currentStatus: that.data.status.cannotConnect
        })
      }
    })
  },

  //蓝牙扫描门禁设备
  scanBluetoothDevice() {
    const that = this;

    bluetoothSortingScan.start("", async(res) => {
      console.log(res, '蓝牙搜索到的门禁设备对象');
      if (res.length > 0) {
        //有权限开门的机器列表 鉴别权限
        console.log('后台请求鉴权');
        const authList = await that.checkPermission(res)

        that.setData({
          deviceList: authList
        })
        if (authList.length <= 0) {
          //列表没有值
          that.setData({
            currentStatus: that.data.status.noDivice
          })
        } else {
          //列表有值
          that.setData({
            currentStatus: that.data.status.opening
          })
          if (this.data.isFirst) {
            that.unlockDoorHandle()
            that.setData({
              isFirst: false
            })
          }
        }
      } else {
        //未找到门禁设备
        console.log('未找到门禁设备');
        that.setData({
          currentStatus: that.data.status.noDivice
        })
      }
    })
  },


  async unlockDoorHandle() {
    if (this.data.currentStatus == this.data.status.success) {
      return
    }

    if (this.data.deviceList.length >= 1) {
      console.log(this.data.deviceList[0].lockName,'door');
      console.log(this.data.deviceList[0],'chooseDevice');

      let tmp = this.data.deviceList[0]
      tmp.deviceName = tmp.name
      //赋值到选择框里
      this.setData({
        door: this.data.deviceList[0].lockName,
        selectInfo: tmp, //选择的开门门禁信息
        actions: this.data.deviceList.map(item => {
          return {
            ...item,
            deviceName: item.name,
            name: item.lockName
          }
        }).slice(0, 5)
      })
    } else {
      console.log('没有权限');
    }
  },

  //设备与用户身份鉴权
  async checkPermission(deviceList) {
    console.log('鉴权开始');
    var that = this;
    let data = {
      locks: deviceList
    }
    const ret = await this.doorPermission(data)
    //const ret = await app.agriknow.sgin_request(ports.doorPermission, data)
    if (ret.status == 1) {
      console.log('鉴权成功');
      console.log(ret.list, 'ret.list');
      return ret.list
    } else {
      console.log('鉴权失败');
      //后台请求报错 返回空数组
      app.showTip(ret.msg);
      return [];
    }
  },


  async doorPermission(deviceList) {
    console.log(deviceList.locks, '传入后台的设备列表');
  
    const that = this;
    const res = await new Promise(function(resolve, reject) {
      wx.request({
        url: that.data.baseUrl + 'doorPermission.php',
        method: 'POST',
        data: {
          'deviceList': JSON.stringify(deviceList.locks),
          'openid': that.data.openid
        },
        header: {
          'content-type': 'application/x-www-form-urlencoded'
        },
        success: function(res) {
          resolve(res.data); // 请求成功，调用resolve方法
        },
        fail: function(res) {
          reject([{
            'status': 0,
            'msg': '服务器繁忙,请稍候重试'
          }]); // 请求失败，调用reject方法,返回一个空数组
        }
      });
    });
    return res;
  },



  //开门操作
  openDoor({
    id,
    deviceId,
    deviceName,
    encryFlag
  }) {
    const that = this
    console.log(id+"**"+deviceId+"**"+deviceName+'**'+encryFlag,'当前开门的门禁信息');
    if (deviceName.startsWith('06')) {
      console.log('1111111111111111');
      // 博西尼设备开门
      bosinyBleOpen.ConnectTo(deviceId, deviceName, 0, function(res) {
        switch (res.state) {
          case 'OK':
            wx.vibrateLong({
              success: (res) => {},
            })
            that.addOpenLockBill(id, 1, '开门 成功')
            break;
          case '002':
            that.addOpenLockBill(id, 0, '未扫描到门禁设备，请确认周围环境已安装门禁设备或者您可以尝试重启蓝牙后在开门')
            break;
          case '003':
            that.addOpenLockBill(id, 0, '发送开门信息失败')
            break;
          case '004':
            that.addOpenLockBill(id, 0, '蓝牙连接失败，请尝试重启蓝牙后在开门')
            break;
          default:
            that.addOpenLockBill(id, 0, '请尝试重启蓝牙后在开门')
            break;
        }
      })
    } else if (deviceName.startsWith('C3') || deviceName.startsWith('C6')) {
      console.log('2222222222222222222222');
      peakeBleOpen.ConnectTo(deviceName, deviceId, function(res) {
        switch (res.state) {
          case 'OK':
            wx.vibrateLong({
              success: (res) => {},
            })
            that.addOpenLockBill(id, 1, '开门 成功')
            break;
          case '002':
            that.addOpenLockBill(id, 0, '未扫描到门禁设备，请确认周围环境已安装门禁设备或者您可以尝试重启蓝牙后在开门')
            break;
          case '003':
            that.addOpenLockBill(id, 0, '连接门禁设备失败，请尝试重启蓝牙后在开门')
            break;
          case '004':
            that.addOpenLockBill(id, 0, '蓝牙连接失败，请尝试重启蓝牙后在开门')
            break;
          default:
            that.addOpenLockBill(id, 0, '请尝试重启蓝牙后在开门')
            break;
        }
      })
    } else {
        console.log('3333333333333');
      inBleOpen.ConnectTo(deviceName, encryFlag, deviceId, function(res) {
        switch (res.state) {
          case 'OK':
            wx.vibrateLong({
              success: (res) => {},
            })
            that.addOpenLockBill(id, 1, '开门 成功')
            break;
          case '002':
            that.addOpenLockBill(id, 0, '未扫描到门禁设备，请确认周围环境已安装门禁设备或者您可以尝试重启蓝牙后在开门')
            break;
          case '003':
            that.addOpenLockBill(id, 0, '连接门禁设备失败，请尝试重启蓝牙后在开门')
            break;
          case '004':
            that.addOpenLockBill(id, 0, '蓝牙连接失败，请尝试重启蓝牙后在开门')
            break;
          default:
            that.addOpenLockBill(id, 0, '请尝试重启蓝牙后在开门')
            break;
        }
      })
    }
  },

  //记录开门日志
  async addOpenLockBill(id, flag, desc) {
    const that = this
    if (flag === 1) {
      that.setData({
        currentStatus: that.data.status.success
      })
    } else {
      this.setData({
        currentStatus: this.data.status.fail
      })
    }
    /*setTimeout(() => {
      that.setData({
        currentStatus: that.data.status.open
      })
    }, 5000);*/
    console.log('记录日志');
    let data = {
      id,
      flag,
      desc
    }

    //const ret = await app.agriknow.sgin_request(ports.addOpenLockBill, data)
    const ret = await that.addOpenLockBillService(id, flag, desc);
    if (ret.status === 1) {} else {
      app.showTip(ret.msg);
    }
  },

  //添加开门记录
  async addOpenLockBillService(id, flag, desc) {
    const that = this;
    const res = await new Promise(function(resolve, reject) {
      wx.request({
        url: that.data.baseUrl + 'addOpenLockBill.php',
        method: 'POST',
        data: {
          'openid': that.data.openid,
          'id': id,
          'flag': flag,
          'desc': desc
        },
        header: {
          'content-type': 'application/x-www-form-urlencoded'
        },
        success: function(res) {
          resolve(res.data); // 请求成功，调用resolve方法
        },
        fail: function(res) {
          reject({
            'status': 0,
            'msg': '服务器繁忙,请稍候重试'
          }); // 请求失败，调用reject方法,返回一个空数组
        }
      });
    });
    return res;
  },



  //选择好了要开启的门禁
  onSheetSelect(event) {
    let row = parseInt(event.detail.value);
    let lockName = this.data.actions[row].lockName;
    let selectInfo = this.data.actions[row];
    this.setData({
      door: lockName,
      selectInfo: selectInfo
    });
  },

  //选择了过后点击确认
  sure() {
    //调用开门
    this.openDoor(this.data.selectInfo);
    this.setData({
      clickOpen:true
    })
  },


  //获取微信分享信息
  getShareInfo() {
    var that = this;
    wx.request({
      url: that.data.baseUrl + 'getShareInfo.php',
      method: 'POST',
      data: {

      },
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function(res) {
        that.setData({
          shareTitle: res.data.shareTitle,
          shareImg: res.data.shareImg
        });
      },
      fail: function(res) {}
    });
  },


  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {
    var that = this;
    return {
      title: that.data.shareTitle,
      path: '/pages/index/index',
      imageUrl: that.data.shareImg,
      success: function(res) {

      },
      fail: function(res) {

      }
    }
  }
})